package LeetCode.LeetCode2;

/**
 * 接雨水
 * @author lumin
 * @date 2022/04/13 10:39
 **/
public class Num42 {
    public static int trap(int[] height) {
        if(height.length <= 1){
            return 0;
        }
        int maxNum = 0;
        for (int i = 0; i < height.length; i++) {
            maxNum = Math.max(maxNum,height[i]);
        }
        int left = 0;
        int right = 1;
        int maxSumLeft = 0;
        int right2 = height.length - 1;
        int left2 = height.length - 2;
        int maxSumRight = 0;
        int maxSum = 0;
        while (right < height.length) {
            if (height[right] >= height[left]) {
                maxSumLeft += (((right - 1) - left) * height[left]) - sumHeight(height, left + 1, right - 1);
                left = right;
            }
            if (height[right] == maxNum) {
                break;
            }
            right++;
        }
        if (right == height.length - 1) {
            return maxSumLeft;
        } else {
            while (left2 >= 0) {
                if (height[left2] >= height[right2]) {
                    maxSumRight += (((right2 - 1) - left2) * height[right2]) - sumHeight(height, left2 + 1, right2 - 1);
                    right2 = left2;
                }
                if (height[left2] == maxNum) {
                    break;
                }
                left2--;
            }
        }
        maxSum = maxSumLeft + maxSumRight;
        if(right != left2 && left2 != 0 && right != height.length - 1){
            maxSum +=  (((left2 - 1) - right) * height[left2]) - sumHeight(height, right + 1, left2 - 1);
        }
        return maxSum;
    }

    private static int sumHeight(int[] height, int left, int right) {
        int num = 0;
        while(left <= right){
            num += height[left];
            left++;
        }
        return num;
    }

    public static void main(String[] args) {
        int[] arr = {4,2,3};
        System.out.println(trap(arr));
    }
}